package com.cskaoyan.service.adminservice.impl;

import com.cskaoyan.bean.common.BasePageInfo;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.po.MarketPermission;
import com.cskaoyan.bean.po.MarketRole;
import com.cskaoyan.bean.po.MarketRoleExample;
import com.cskaoyan.bean.chaosbean.role.permissions.vo.PerBO;
import com.cskaoyan.bean.chaosbean.role.permissions.vo.PerVO;
import com.cskaoyan.bean.chaosbean.storage.vo.StorageListVO;
import com.cskaoyan.bean.chaosbean.system.vo.SystemOptionsVO;
import com.cskaoyan.mapper.MarketRoleMapper;
import com.cskaoyan.service.adminservice.RoleService;
import com.cskaoyan.util.StringUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jackX
 * @datetime 2022/12/28 18:57
 * @description: TODO:
 */
@Component
public class RoleServiceImpl implements RoleService {
    @Autowired
    MarketRoleMapper marketRoleMapper;

    /**
     * /admin/role/options
     *
     * @return
     */
    @Override
    public SystemOptionsVO selectOptions() {
        SystemOptionsVO vo = new SystemOptionsVO();
        List<SystemOptionsVO.ListBean> list = marketRoleMapper.selectAuth();
        PageInfo<SystemOptionsVO.ListBean> pageInfo = new PageInfo<>(list);
        vo.setList(list);
        vo.setLimit(pageInfo.getPageSize());//limit
        vo.setPage(pageInfo.getPageNum());//page
        vo.setPages(pageInfo.getPages());//pages
        vo.setTotal((int) pageInfo.getTotal());//total
        return vo;
    }

    @Override
    public StorageListVO selectInfo(BasePageInfo info, String name) {
        //开启分页
        PageHelper.startPage(info.getPage(), info.getLimit());
        MarketRole role = new MarketRole();
        StorageListVO listVO = new StorageListVO();
        MarketRoleExample example = new MarketRoleExample();
        //排序
        example.setOrderByClause(info.getSort() + " " + info.getOrder());
        MarketRoleExample.Criteria criteria = example.createCriteria();
        if (!StringUtil.isEmpty(name)) {
            criteria.andNameLike(name);
        }
        List<MarketRole> list = marketRoleMapper.selectByExample(example);
        listVO.setList(list);
        PageInfo<MarketRole> pageInfo = new PageInfo<>(list);
        listVO.setLimit(pageInfo.getPageSize());//limit
        listVO.setPage(pageInfo.getPageNum());//page
        listVO.setPages(pageInfo.getPages());//pages
        listVO.setTotal((int) pageInfo.getTotal());//total
        return listVO;
    }

    @Override
    public BaseRespVo create(MarketRole role) {
        BaseRespVo baseRespVo = new BaseRespVo();
        MarketRole roleName = marketRoleMapper.selectByName(role);
        if (roleName != null) {
            baseRespVo.setErrno(640);
            baseRespVo.setErrmsg("角色已经存在");
            return baseRespVo;
        }
        MarketRole marketRole = new MarketRole(null, role.getName(), role.getDesc(), false, new Date(), new Date(), true);
        marketRoleMapper.insert(marketRole);
        baseRespVo.setErrno(0);
        baseRespVo.setData(marketRole);
        baseRespVo.setErrmsg("成功");
        return baseRespVo;
    }

    @Override
    public BaseRespVo update(MarketRole role) {
        BaseRespVo baseRespVo = new BaseRespVo();

        try {
            marketRoleMapper.updateByPrimaryKey(role);
        } catch (Exception e) {
            baseRespVo.setErrno(502);
            baseRespVo.setErrmsg("角色名称重复了");
            return baseRespVo;
        }
        baseRespVo.setErrno(0);
        baseRespVo.setData(role);
        baseRespVo.setErrmsg("成功");
        return baseRespVo;
    }

    @Override
    public void delete(MarketRole role) {
        marketRoleMapper.deleteByPrimaryKey(role.getId());
    }

    @Override
    public PerVO selectPer(Integer roleId) {
        PerVO vo = new PerVO();
        System.out.println("roleId = " + roleId);
        List<String> assignedPer = null;
        if (roleId == 1) {
            assignedPer = marketRoleMapper.selectAllPer();
        } else {
            assignedPer = marketRoleMapper.selectPer(roleId);
        }
        //先查最外层systemPermissions  需要返回 market_detail_permission 表中的 model_id,model_label  返回VO：id;label;
        List<PerVO.SystemPermissionsBean> outer = marketRoleMapper.selectOuterDetail();
        //循环封装
        for (int i = 0; i < outer.size(); i++) {
            //在查询中间层的数据 需要返回 market_detail_permission 表中的 function_id,function_label 返回VO：id;label;
            List<PerVO.SystemPermissionsBean.ChildrenBeanX> mid = marketRoleMapper.selectMidDetail(outer.get(i).getId());
            //循环封装
            for (int j = 0; j < mid.size(); j++) {
                //查询最内层数据 需要返回 market_detail_permission 表中的 api,detail_id,label ,返回的VO api,id,label
                List<PerVO.SystemPermissionsBean.ChildrenBeanX.ChildrenBean> inner = marketRoleMapper.selectInnerDetail(mid.get(j).getLabel());
                //内层数据封装到中间层
                mid.get(j).setChildren(inner);
            }
            //中间层数据封装到最外层
            outer.get(i).setChildren(mid);
        }
        //最后封装
        vo.setSystemPermissions(outer);
        vo.setAssignedPermissions(assignedPer);
        return vo;
    }

    @Override
    public void updateRolePer(MarketPermission per) {
        //查询出表中的数据
        List<String> list = marketRoleMapper.selectPerAll(per.getRoleId());
        //根据传进来的roleId进行全部逻辑删除
        marketRoleMapper.updateAllDel(per.getRoleId());
        //参数传递过来的数据

        List<String> perPermissions = Arrays.asList(per.getPermissions());
        ArrayList<String> identical = new ArrayList<>();

        //数据库中查询出的数据
        for (String s : list) {
            for (String permission : perPermissions) {
                if (!StringUtil.isEmpty(s) || StringUtil.isEmpty(permission)) {
                    if (s.equals(permission)) {
                        //存储表中已有的相同数据
                        identical.add(s);
                    }
                }
            }
        }

        List<String> different = perPermissions.stream().filter(item -> !list.contains(item)).collect(Collectors.toList());

        //将相同的数据进行逻辑添加
        if (identical.size() != 0) {
            marketRoleMapper.updateIn(per.getRoleId(), identical);
        }
        //不同的数进行逻辑插入
        if (different.size() != 0) {
            for (int i = 0; i < different.size(); i++) {
                marketRoleMapper.insertPer(new PerBO(null, per.getRoleId(), different.get(i), new Date(), new Date(), false));
            }
        }

    }

}

